package com.forward;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageTree;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class PdfToImageConverter {
    public static void main(String[] args) {
        String pdfFolder = "data/";
        String outputFolder = "output_pdfs";
        convertPdfLastPagesToPdfs(pdfFolder, outputFolder);
    }

    public static void convertPdfLastPagesToPdfs(String pdfFolderPath, String outputFolderPath) {
        Path pdfFolder = Paths.get(pdfFolderPath);
        Path outputFolder = Paths.get(outputFolderPath);

        try {
            // 创建输出文件夹
            if (!Files.exists(outputFolder)) {
                Files.createDirectories(outputFolder);
            }

            // 遍历 PDF 文件夹中的所有文件
            File[] pdfFiles = new File(pdfFolderPath).listFiles((dir, name) -> name.toLowerCase().endsWith(".pdf"));
            if (pdfFiles != null) {
                for (File pdfFile : pdfFiles) {
                    try (PDDocument document = PDDocument.load(pdfFile)) {
                        int lastPageIndex = document.getNumberOfPages() - 1;
                        if (lastPageIndex >= 0) {
                            PDDocument lastPageDoc = new PDDocument();
                            PDPageTree pages = document.getPages();
                            PDPage lastPage = pages.get(lastPageIndex);
                            lastPageDoc.addPage(lastPage);

                            String pdfFileName = pdfFile.getName().replaceFirst("[.][^.]+$", "") + "+技术经济指标综合评分及排序表.pdf";
                            Path pdfPath = outputFolder.resolve(pdfFileName);
                            lastPageDoc.save(pdfPath.toFile());
                            lastPageDoc.close();
                            System.out.println("保存 " + pdfFileName + " 成功");
                        }
                    } catch (IOException e) {
                        System.err.println("处理 " + pdfFile.getName() + " 时出错: " + e.getMessage());
                    }
                }
            }
        } catch (IOException e) {
            System.err.println("创建输出文件夹时出错: " + e.getMessage());
        }
    }
}    